<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="80px">
      <el-row>
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <!-- <el-form-item label="状态" prop="dataStatus">
          <el-select
            v-model="queryParams.dataStatus"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item style="margin-left: 22px">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5" style="margin-left: 10px">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:brand:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:brand:remove']"
          >删除</el-button
        >
      </el-col> -->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务图标" align="center" prop="taskIcon" width="100">
          <template slot-scope="scope">
            <el-image v-if="scope.row.taskIcon != null && scope.row.taskIcon != ''" slot="reference"
              :src="scope.row.taskIcon" class="image-rows" :preview-src-list="[scope.row.taskIcon]"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="任务名称" align="center" prop="taskName" />
        <el-table-column label="任务代码" align="center" prop="taskCodeStr" />

        <el-table-column label="任务简介" align="center" prop="taskBrief" />

        <el-table-column label="开始时间-结束时间" align="center" prop="timeStr" width="260px" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startDate, "{y}年{m}月{d}日") }}-
              {{ parseTime(scope.row.endDate, "{y}年{m}月{d}日") }}</span>
          </template>
        </el-table-column>

        <el-table-column label="显示顺序" align="center" prop="taskSort" width="80"/>

        <el-table-column label="任务奖励" align="center" prop="reward" />

        <el-table-column label="是否展示" align="center" prop="isShow" width="80">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isShow" active-value="1" inactive-value="0"
              @change="handleShowChange(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="数据状态" align="center" prop="dataStatus" width="80">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.dataStatus" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>



        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-if="scope.row.dataStatus == '0'" size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改任务/系列对话框 -->
    <el-dialog z-index="1000" :title="title" :visible.sync="open" width="1250px" append-to-body
      @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" class="select-normal" maxlength="20"
            show-word-limit />
        </el-form-item>

        <el-form-item label="任务代码" prop="taskCode">
          <el-select v-model="form.taskCode" placeholder="请选择任务代码" clearable size="small">
            <el-option v-for="dict in taskOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item label="任务简介" prop="taskBrief">
          <el-input v-model="form.taskBrief" placeholder="请输入任务简介" style="width: 400px" maxlength="100"
            show-word-limit />
        </el-form-item>

        <el-form-item label="任务Icon">
          <imageArraySize :imageStr.sync="form.taskIcon" :key="form.taskIcon" :width="112" :height="112"
            :msg="'图片要求：宽112px高112px，大小1M内。'" :limit="1" ref="childs"></imageArraySize>
        </el-form-item>

        <el-form-item label="任务时间" prop="startDate">
          <el-date-picker v-model="form.timeValue" type="datetimerange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" @change="getSTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="权益" prop="rightType">
          <el-radio-group v-model="form.rightType" @change="reduce">
            <el-radio label="score">菠萝派</el-radio>
            <el-radio label="coupon">优惠券</el-radio>
            <el-radio label="card">套餐卡</el-radio>
            <el-radio label="service">服务项目</el-radio>
            <el-radio label="product">商品</el-radio>
          </el-radio-group>

        </el-form-item>

        <el-form-item label="菠萝派数量" prop="score" v-if="form.rightType == 'score'">
          <el-input-number :controls="false" :precision="0" :step="0" :min="1" :max="999" v-model="form.score">
          </el-input-number>
        </el-form-item>

        <el-form-item label="经验值数量" prop="expValue" v-if="form.rightType == 'expValue'">
          <el-input-number :controls="false" :precision="0" :step="0" :min="1" :max="999999" v-model="form.expValue">
          </el-input-number>
        </el-form-item>

        <!-- <el-form-item label="奖励" prop="reward"
          v-if="form.rightType != 'score' && form.rightType != 'expValue' && form.taskId != null">
          <el-input-number disabled :controls="false" :precision="0" :step="0" :min="0" :max="999999"
            v-model="form.reward"></el-input-number>
        </el-form-item> -->

        <el-form-item label="优惠券" v-if="form.rightType == 'coupon'">
          <el-button style="margin-bottom:10px" type="primary" @click="selectCommodityCoupon">选择优惠券</el-button>
          <selectedCoupon style="margin-top: 10px;" ref="childCoupon"
            v-if="Object.keys(this.selectedDataCoupon).length > 0" :selectedData="selectedDataCoupon"
            @tabRespon="tabResponCoupon">
          </selectedCoupon>
        </el-form-item>
        <commodityCoupon v-if="couponOpen" @toCloseBox="toCloseBoxCoupon" @multipleSelection="multipleSelectionCoupon"
          :flag="couponOpen" :source="false" ref="selTableCoupon"></commodityCoupon>

        <el-form-item label="套餐卡" v-if="form.rightType == 'card'">
          <el-button style="margin-bottom:10px" type="primary" @click="selectCommodityCard">选择套餐卡</el-button>
          <selectedCard ref="childStore" style="margin-top: 10px" v-if="Object.keys(this.selectedDataCard).length > 0"
            :selectedData="selectedDataCard" @tabRespon="tabResponCard">
          </selectedCard>
        </el-form-item>
        <commodityCard v-if="openCard" @toCloseBox="openCard = false" @multipleSelection="multipleSelectionCard"
          :flag="openCard" ref="selTableCardUpdate">
        </commodityCard>

        <el-form-item label="服务项目" v-if="form.rightType == 'service'">
          <el-button style="margin-bottom:10px" type="primary" @click="selectCommodityService">选择服务项目</el-button>
          <selectedA ref="childStore" style="margin-top: 10px" v-if="Object.keys(this.selectedDataStore).length > 0"
            :selectedData="selectedDataStore" @tabRespon="tabResponItem">
          </selectedA>
        </el-form-item>
        <commodityItem v-if="storeOpen" @toCloseBox="toCloseBoxStore" @multipleSelection="multipleSelectionStore"
          :flag="storeOpen" :source="false" ref="selTableItem"></commodityItem>

        <el-form-item label="商品" v-if="form.rightType == 'product'">
          <el-button style="margin-bottom:10px" type="primary" @click="selectCommodity">选择商品</el-button>
          <selectedPro v-if="Object.keys(this.selectedData).length > 0" :selectedData="selectedData"
            :destroy-on-close="true" @tabRespon="tabResponProduct">
          </selectedPro>
        </el-form-item>
        <commoditytab v-if="openA" @toCloseBox="toCloseBox" @multipleSelection="multipleSelection" :flag="openA"
          ref="selTable"></commoditytab>

        <el-form-item label="显示顺序" prop="taskSort">
          <el-input-number v-model="form.taskSort" controls-position="right" @change="handleChange" :min="1" :max="10">
          </el-input-number>
        </el-form-item>

        <el-form-item label="任务详情">
          <editor v-model="form.taskDesc" :min-height="192" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
  updateTaskStatus,
  getCard,
  getItem,
  getCoupon,
  getInfo
} from "@/api/service/task";
import Editor from "@/components/Editor";
import commoditytab from "@/components/radio/commodityPro";
import selectedPro from "@/components/radio/SelectedPro";
import selectedA from "@/components/radio/SelectedItem";
import commodityItem from "@/components/radio/commodityItem";
import commodityCard from "@/components/radio/commodityCard";
import selectedCard from "@/components/radio/SelectedCard";
import selectedCoupon from "@/components/radio/SelectedCoupon";
import commodityCoupon from "@/components/radio/commodityCoupon";
import imageArraySize from "@/components/ImageUpload/imageArraySize";
export default {
  name: "Task",
  components: {
    imageArraySize,
    Editor,
    commoditytab,
    selectedPro,
    selectedA,
    commodityItem,
    selectedCoupon,
    commodityCoupon,
    selectedCard,
    commodityCard,
  },
  data() {
    return {
      selectedDataCopy: [{}],
      selectedData: {},
      selectedDataCard: {},
      storeOpen: false,
      selectedDataStore: {},
      couponOpen: false,
      selectedDataCoupon: {},

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中数组的名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务/系列表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openA: false,
      openCard: false,
      // 用于类别关联的分类显示
      dialogVisible: false,
      //常用状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        dataStatus: null,
      },
      q: null,
      // options: [
      //   {
      //     value: "1",
      //     label: "独占",
      //   },
      //   {
      //     value: "0",
      //     label: "非独占",
      //   },
      // ],
      // optionsA: [
      //   {
      //     value: "1",
      //     label: "能量",
      //   },
      //   {
      //     value: "0",
      //     label: "非能量",
      //   },
      // ],
      // 表单参数
      form: {
        dialogImageUrl: "",
        dataPriority: "",
        rightType: ''
      },
      // 表单校验
      rules: {
        taskCode: [
          {
            required: true,
            message: "请选择任务代码",
            trigger: "blur",
          }
        ],
        rightType: [
          {
            required: true,
            message: "请选择权益",
            trigger: "blur",
          }
        ],
        taskName: [
          {
            required: true,
            message: "任务名称不能为空",
            trigger: "blur",
          },
        ],
        dataPriority: [
          {
            required: true,
            message: "排序不能为空",
            trigger: "blur",
          },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      taskOptions: [],
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_data_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_task").then((response) => {
      this.taskOptions = response.data;
    });
  },
  methods: {
    selectCommodityCoupon() {
      this.$forceUpdate();
      this.couponOpen = true;
      console.log(this.couponOpen);
      this.$nextTick(() => {
        this.$refs["selTableCoupon"].greet(this.selectedDataCoupon);
      });
    },

    //调用子组件中方法，向子组件传值
    selectCommodity() {
      this.$forceUpdate();
      this.openA = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedData);
      });
    },

    selectCommodityCard() {
      this.$forceUpdate();
      this.openCard = true;
      this.$nextTick(() => {
        this.$refs["selTableCardUpdate"].greet(this.selectedDataCard);
      });
    },

    multipleSelectionCard(data) {
      this.openCard = false;
      this.selectedDataCard = data;
      console.log(data);
      // this.$nextTick(() => {
      //   this.$refs.child.getList();
      // });
    },

    multipleSelection(data) {
      this.openA = false;
      this.selectedData = data;
    },

    selectCommodityService() {
      this.$forceUpdate();
      this.storeOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableItem"].greet(this.selectedDataStore);
      });
    },

    toCloseBoxCoupon() {
      this.couponOpen = false;
    },

    toCloseBoxCard() {
      this.openCard = false;
    },

    toCloseBoxStore() {
      this.storeOpen = false;
    },

    toCloseBox() {
      this.openA = false;
    },

    multipleSelectionCoupon(data) {
      this.couponOpen = false;
      this.selectedDataCoupon = data;
      this.$nextTick(() => {
        this.$refs.childCoupon.getList();
      });
    },

    multipleSelectionStore(data) {
      this.storeOpen = false;
      this.selectedDataStore = data;
      this.$nextTick(() => {
        this.$refs.childStore.getList();
      });
    },

    dataPriorityInput(value) {
      let js = value + "";
      return js.replace(/^(0+)|[^\d]+/g, "");
    },
    /** 查询任务/系列列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then((response) => {
        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleRemove(file, fileList) { },
    handlePictureCardPreviewLogo(file) {
      this.logoUr = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewImg(file) {
      this.taskIcon = file.url;
      this.dialogVisible = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    p(s) {
      return s < 10 ? "0" + s : s;
    },

    // 关联的取消按钮
    cancelTask() {
      this.openTask = false;
      this.reset();
    },
    handleChange(value) {
      console.log(value);
    },

    reduce(e) {
      console.log(e, '====')
      this.selectedData = {}
      this.selectedDataCard = {}
      this.selectedDataCoupon = {}
      this.selectedDataStore = {}
      this.form.score = null
      this.form.expValue = null
      this.form.serviceItemId = null
      this.form.cardId = null
      this.form.couponId = null
      this.form.productId = null
    },

    getSTime(val) {
      //手动赋值，使其通过校验

      const d = new Date(val[0]);
      const resDate =
        d.getFullYear() +
        "-" +
        this.p(d.getMonth() + 1) +
        "-" +
        this.p(d.getDate());
      const resTime =
        this.p(d.getHours()) +
        ":" +
        this.p(d.getMinutes()) +
        ":" +
        this.p(d.getSeconds());
      this.form.startDate = resDate + " " + resTime;
      const c = new Date(val[1]);
      const resDatec =
        c.getFullYear() +
        "-" +
        this.p(c.getMonth() + 1) +
        "-" +
        this.p(c.getDate());
      const resTimec =
        this.p(c.getHours()) +
        ":" +
        this.p(c.getMinutes()) +
        ":" +
        this.p(c.getSeconds());
      this.form.endDate = resDatec + " " + resTimec;
    },

    handleSportRecord(row) {
      // this.$router.push({ path: "/service/taskRecommend/index" + row.taskId });
      this.$router.push({
        path: "/centre/taskManger/service/taskRecommend",
        query: {
          backName: row.taskId,
        },
      });
    },

    // 表单重置
    reset() {
      this.form = {
        deviceName: null,
        logoUrl: null,
        deviceTask: null,
        taskIcon: null,
        dataPriority: 10,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 任务菜单 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.taskId);
      this.names = selection.map((item) => item.deviceName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.dataStatus) {
            this.multiple = true;
            break;
          }
        }
      }
    },
    handleShowChange(row) {
      let text = row.isShow === "0" ? "隐藏" : "显示";
      this.$confirm(
        '确定要把任务名称为"' + row.taskName + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          let data = {
            taskId: row.taskId, isShow: row.isShow
          }
          return updateTaskStatus(data);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.isShow = row.isShow === "0" ? "1" : "0";
        });
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.dataStatus === "0" ? "无效" : "有效";
      this.$confirm(
        '确定要把任务名称为"' + row.taskName + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          let data = {
            taskId: row.taskId, dataStatus: row.dataStatus
          }
          return updateTaskStatus(data);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taskId = row.taskId || this.ids;
      getTask(taskId).then((response) => {
        this.form = response.data;
        this.$set(this.form, 'timeValue', [])
        if (this.form.startDate) {
          this.form.timeValue.push(this.form.startDate);
          this.form.timeValue.push(this.form.endDate);
        }

        this.selectedData = {}
        this.selectedDataCard = {}
        this.selectedDataCoupon = {}
        this.selectedDataStore = {}
        if (this.form.score != null) {
          this.$set(this.form, 'rightType', 'score')
        }

        if (this.form.expValue != null) {
          this.$set(this.form, 'rightType', 'expValue')
        }

        if (this.form.serviceItemId != null) {
          this.$set(this.form, 'rightType', 'service')
          getItem(this.form.serviceItemId).then((response) => {
            this.selectedDataStore = response.data;
          });
        }

        if (this.form.cardId != null) {
          this.$set(this.form, 'rightType', 'card')
          getCard(this.form.cardId).then((response) => {
            this.selectedDataCard = response.data;
          });
        }

        if (this.form.couponId != null) {
          this.$set(this.form, 'rightType', 'coupon')
          getCoupon(this.form.couponId).then((response) => {
            this.selectedDataCoupon = response.data;
          });
        }

        if (this.form.productId != null) {
          this.$set(this.form, 'rightType', 'product')
          getInfo(this.form.productId).then((response) => {
            this.selectedData = response.data;
          });
        }

        this.open = true;
        this.title = "修改任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.childs.selectImgs();
      this.$refs["form"].validate((valid) => {
        if (valid) {

          if (this.selectedDataCard) {
            this.form.cardId = this.selectedDataCard.cardId;
          }
          if (this.selectedData) {
            this.form.productId = this.selectedData.productUid;
          }
          if (this.selectedDataCoupon) {
            this.form.couponId = this.selectedDataCoupon.couponUid;
          }
          if (this.selectedDataStore) {
            this.form.serviceItemId = this.selectedDataStore.itemId;
          }

          if (this.form.score == null && this.form.score != 0 && this.form.expValue != 0 && this.form.expValue == null && this.form.serviceItemId == null && this.form.cardId == null
            && this.form.couponId == null && this.form.productId == null
          ) {
            this.$message.error("请选择对应的权益或者填写对应的值");
            return
          }

          if (this.form.taskId != null) {
            updateTask(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.taskId || this.ids;
      const names = row.taskName || this.names;
      this.$confirm('是否确认删除任务名称为"' + names + '"的任务?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delTask(deviceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "device/brand/export",
        {
          ...this.queryParams,
        },
        `商品任务.xlsx`
      );
    },
    tabResponCoupon() {
      this.selectedDataCoupon = {};
    },
    tabResponCard() {
      this.selectedDataCard = {}
    }, tabResponItem() {
      this.selectedDataStore = {}
    }, tabResponProduct() {
      this.selectedData = {}
    },
  },
};
</script>
<style lang="scss" scoped>
.treeOne {
  display: inline-block;
  margin-right: 200px;
}

.treeTwo {
  display: inline-block;
}

.image-rows {
  width: 60px;
  height: 60px;
}
</style>
